package com.otdemo.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.otdemo.dao.RestContentDao;
import com.otdemo.dao.RestUserDao;
import com.otdemo.entity.RestContent;
import com.otdemo.entity.RestUser;
import com.otdemo.resp.ResultResponse;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/content/edit")
public class ContentEditController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        String uid = req.getParameter("uid");
        RestContent rest = new RestContentDao().findByUid(uid);
        req.setAttribute("rest", rest);
        req.getRequestDispatcher("/ContentEdit.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        RestContent rest = new ObjectMapper().readValue(s, RestContent.class);
        new RestContentDao().update(rest);
        ResultResponse resultResponse = new ResultResponse();
        resp.getWriter().write(new ObjectMapper().writeValueAsString(resultResponse.success()));
    }
}
